<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="filters.phoneNumber" placeholder="手机号码" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <org-unit-select v-model="filters.orgUnitId" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleAdd">注册/邀请用户</el-button>
      <div style="margin-left: 3.125rem;">
        <el-checkbox v-for="col in dynamicColumn.user" v-model="col.show" class="filter-item" style="margin-left:10px;" @change="tableKey=tableKey+1">
          {{ col.name }}
        </el-checkbox>
      </div>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      border
      fit
      :height="tableHeight"
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="selsChange"
    >
      <el-table-column type="index" width="60" />
      <el-table-column v-if="showPhoneNumber" prop="phoneNumber" label="手机号码" width="120" />
      <el-table-column prop="nickname" label="昵称" min-width="160" />
      <el-table-column prop="roles" label="角色" min-width="220" :formatter="formatRoles" />
      <el-table-column prop="orgUnitName" label="组织" min-width="320" />
      <el-table-column prop="disabled" label="状态" width="80" :formatter="formatDisabled" />
      <el-table-column v-if="checkColumn('registerTime')" prop="registerTime" label="注册时间" width="180" />
      <el-table-column v-if="checkColumn('operation')" label="操作" width="360" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" @click="handleRoleDetails(scope.index, scope.row)">角色列表</el-button>
          <el-button size="small" @click="handleAddRole(scope.index, scope.row)">授权角色</el-button>
          <el-button size="small" @click="handleResetPwd(scope.index, scope.row)">重置密码</el-button>
          <el-button v-if="canChangeDisabled && scope.row.disabled === 1" size="small" @click="enable(scope.index, scope.row)">启用</el-button>
          <el-button v-if="canChangeDisabled && scope.row.disabled === 0" size="small" @click="disable(scope.index, scope.row)">禁用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filters.page" :limit.sync="filters.limit" @pagination="loadPageList" />

    <el-dialog title="用户信息" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :label-width="formLabelWidth" :rules="addFormRules">
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="addForm.phoneNumber" auto-complete="off" />
        </el-form-item>
        <el-form-item label="组织" prop="orgUnitId">
          <org-unit-select ref="orgUnitSelector" v-model="addForm.orgUnitId" />
        </el-form-item>
        <el-form-item v-if="recordId===0" label="角色" prop="role">
          <el-select v-model="addForm.role" placeholder="请选择角色">
            <el-option
              v-for="item in roles"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="addLoading" @click="addSubmit">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="editUserNameRoleTitle" :visible.sync="roleListVisible" :close-on-click-modal="false">
      <el-table
        v-loading="roleListLoading"
        border
        fit
        :height="360"
        :data="roleList"
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column prop="role" label="角色" min-width="180" :formatter="formatRole" />
        <el-table-column prop="orgUnitName" label="组织" min-width="260" />
        <el-table-column label="操作" width="120" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="small" @click="deleteUserOfRole(scope.index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleListVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, saveUser, modifyUser, resetPwd, enable, disable } from '@/api/user'
import { listUserRoles, deleteUserRole } from '@/api/user-roles'
import OrgUnitSelect from '../components/org-unit-select'
import waves from '@/directive/waves' // waves directive
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'Users',
  components: { Pagination, OrgUnitSelect },
  directives: { waves },
  data() {
    return {
      tableHeight: 260,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      sels: [], // 列表选中列
      filters: {
        page: 1,
        limit: 20,
        phoneNumber: '',
        orgUnitId: null
      },
      orderBy: {
        orderColumn: '',
        order: ''
      },
      addFormVisible: false,
      addLoading: false,
      addFormRules: {
        phoneNumber: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        orgUnitId: [{ required: true, message: '请选择组织', trigger: 'change' }],
        role: [{ required: true, message: '请选择角色', trigger: 'change' }]
      },
      recordId: 0,
      addForm: {
        phoneNumber: '',
        role: '',
        orgUnitId: null
      },
      allRoles: [{ value: 'Admin', label: '超级管理员' }, { value: 'Manager', label: '管理员' }, { value: 'ShopManager', label: '店长' },
        { value: 'CarpoolMaster', label: '拼车管理员' }, { value: 'CustomerService', label: '客服' },
        { value: 'DM', label: '主持人' }, { value: 'Author', label: '剧本作者' }, { value: 'Player', label: '玩家' }],
      roles: [],
      roleListVisible: false,
      roleListLoading: false,
      roleList: [],
      editUserNameRoleTitle: '用户角色'
    }
  },
  computed: {
    ...mapGetters(['formLabelWidth', 'dynamicColumn', 'userInfo']),
    canChangeDisabled() {
      const roles = this.userInfo.roles || []
      return roles.indexOf('Admin') !== -1
    },
    showPhoneNumber() {
      const roles = this.userInfo.roles || []
      return roles.indexOf('Admin') !== -1 || roles.indexOf('Manager') !== -1
    }
  },
  watch: {
    'addForm.orgUnitId': function(newVal, oldVal) {
      const org = this.$refs.orgUnitSelector.orgUnitItem(newVal)
      if (org) {
        this.initRoles(org.type)
      } else {
        this.initRoles(null)
      }
      this.addForm.role = null
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 220
    this.loadPageList()
    this.initRoles()
  },
  methods: {
    formatRoles(row) {
      if (row.roles && row.roles.length > 0) {
        return this.allRoles.filter(item => row.roles.indexOf(item.value) !== -1).map(item => item.label).join(';')
      }
      return ''
    },
    formatRole(row) {
      if (row.role) {
        return this.allRoles.filter(item => row.role === item.value).map(item => item.label).join(';')
      }
      return ''
    },
    formatDisabled(row) {
      const st = parseInt(row.disabled)
      if (st === 0) {
        return '启用'
      } else if (st === 1) {
        return '禁用'
      }
      return ''
    },
    checkColumn(col) {
      if (this.dynamicColumn.user.hasOwnProperty(col)) {
        return this.dynamicColumn.user[col].show
      }
      return true
    },
    initRoles(orgType) {
      const rs = this.userInfo.roles || []
      if (rs.indexOf('Admin') !== -1) {
        if (orgType) {
          if (orgType === 2) {
            // 选择的组织是加盟商,只能是管理员和剧本作者
            this.roles = [{ value: 'Manager', label: '管理员' }, { value: 'Author', label: '剧本作者' }]
          } else if (orgType === 1) {
            // 选择的是店铺
            this.roles = [{ value: 'Manager', label: '管理员' }, { value: 'ShopManager', label: '店长' }, { value: 'CarpoolMaster', label: '拼车管理员' }, { value: 'CustomerService', label: '客服' }, { value: 'DM', label: '主持人' }]
          }
        } else {
          this.roles = [{ value: 'Manager', label: '管理员' }, { value: 'ShopManager', label: '店长' }, { value: 'CarpoolMaster', label: '拼车管理员' }, { value: 'CustomerService', label: '客服' }, { value: 'DM', label: '主持人' }, { value: 'Author', label: '剧本作者' }]
        }
      } else if (rs.indexOf('Manager') !== -1) {
        if (this.userInfo.orgUnitType === 2) {
          if (orgType) {
            if (orgType === 2) {
              // 选择的组织是加盟商,只能是剧本作者
              this.roles = [{ value: 'Author', label: '剧本作者' }]
            } else if (orgType === 1) {
              // 选择的组织是店铺,只能是店铺管理员、店长、拼车管理员、客服、主持人
              this.roles = [{ value: 'Manager', label: '管理员' }, { value: 'ShopManager', label: '店长' }, { value: 'CarpoolMaster', label: '拼车管理员' }, { value: 'CustomerService', label: '客服' }, { value: 'DM', label: '主持人' }]
            }
          } else {
            // 加盟商管理员,只能添加店铺管理员、店长、主持人、剧本作者
            this.roles = [{ value: 'Manager', label: '管理员' }, { value: 'ShopManager', label: '店长' }, { value: 'CarpoolMaster', label: '拼车管理员' }, { value: 'CustomerService', label: '客服' }, { value: 'DM', label: '主持人' }, { value: 'Author', label: '剧本作者' }]
          }
        } else {
          // 店铺管理员,只能添加店长、主持人
          this.roles = [{ value: 'ShopManager', label: '店长' }, { value: 'CarpoolMaster', label: '拼车管理员' }, { value: 'CustomerService', label: '客服' }, { value: 'DM', label: '主持人' }]
        }
      } else if (rs.indexOf('ShopManager') !== -1) {
        this.roles = [{ value: 'CarpoolMaster', label: '拼车管理员' }, { value: 'CustomerService', label: '客服' }, { value: 'DM', label: '主持人' }]
      }
    },
    loadPageList() {
      this.listLoading = true
      const param = { ...this.filters, ...this.orderBy }
      listUser(param).then(({ success, message, data }) => {
        this.listLoading = false
        if (success) {
          const { records, total } = data || {}
          this.list = records
          this.total = total
        } else {
          this.$message({
            message: message || '查询列表失败',
            type: 'error'
          })
        }
      }, () => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.filters.page = 1
      this.loadPageList()
    },
    sortChange({ prop, order }) {
      this.orderBy.orderColumn = prop
      this.orderBy.order = order
      this.handleFilter()
    },
    selsChange(sels) {
      this.sels = sels
    },
    handleAdd() {
      this.addFormVisible = true
      this.recordId = 0
      this.addFormRules.role[0].required = true
      this.addForm = {
        phoneNumber: '',
        role: '',
        orgUnitId: null
      }
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    handleEdit(index, row) {
      this.addFormVisible = true
      this.recordId = row.id
      this.addForm.phoneNumber = row.phoneNumber
      this.addForm.orgUnitId = row.orgUnitId
      this.addFormRules.role[0].required = false
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    addSubmit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            if (this.recordId) {
              this.doEdit()
            } else {
              this.doAdd()
            }
          })
        }
      })
    },
    doAdd() {
      saveUser({ ...this.addForm }).then(({ success, message }) => {
        this.addLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.$refs['addForm'].resetFields()
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '保存失败',
            type: 'error'
          })
        }
      }, () => {
        this.addLoading = false
      })
    },
    doEdit() {
      modifyUser(this.recordId, this.addForm).then(({ success, message }) => {
        this.addLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.$refs['addForm'].resetFields()
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '修改失败',
            type: 'error'
          })
        }
      }, () => {
        this.addLoading = false
      })
    },
    handleRoleDetails(index, row) {
      this.roleListVisible = true
      this.editUserNameRoleTitle = '用户[' + row.phoneNumber + ']的角色'
      this.loadRoleList(row.id)
    },
    loadRoleList(userId) {
      this.roleListLoading = true
      listUserRoles(userId).then(({ success, message, data }) => {
        this.roleListLoading = false
        if (success) {
          this.roleList = data || []
        } else {
          this.$message({
            message: message || '查询用户角色失败',
            type: 'error'
          })
        }
      }, () => {
        this.roleListLoading = false
      })
    },
    handleAddRole(index, row) {
      this.addFormVisible = true
      this.recordId = 0
      this.addFormRules.role[0].required = true
      this.addForm = {
        phoneNumber: row.phoneNumber,
        role: '',
        orgUnitId: null
      }
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    handleResetPwd(index, row) {
      this.$confirm('确认重置用户密码吗？', '提示', {}).then(() => {
        this.listLoading = true
        resetPwd(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.$message({
              message: message || '重置密码成功',
              type: 'success'
            })
            this.loadPageList()
          } else {
            this.$message({
              message: message || '重置密码失败',
              type: 'error'
            })
          }
        }, () => {
          this.listLoading = false
        })
      })
    },
    deleteUserOfRole(index, row) {
      this.$confirm('确认删除记录吗？', '提示', {}).then(() => {
        this.roleListLoading = true
        deleteUserRole(row.id).then(({ success, message }) => {
          this.roleListLoading = false
          if (success) {
            this.$message({
              message: message || '删除成功',
              type: 'success'
            })
            this.roleListVisible = false
            this.loadPageList()
          } else {
            this.$message({
              message: message || '删除失败',
              type: 'error'
            })
          }
        }, () => {
          this.roleListLoading = false
        })
      })
    },
    enable(index, row) {
      this.$confirm('确认启用吗？', '提示', {}).then(() => {
        this.listLoading = true
        enable(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.loadPageList()
          } else {
            this.$message({
              message: message || '操作失败',
              type: 'error'
            })
          }
        }, () => {
          this.listLoading = false
        })
      })
    },
    disable(index, row) {
      this.$confirm('确认禁止吗？', '提示', {}).then(() => {
        this.listLoading = true
        disable(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.loadPageList()
          } else {
            this.$message({
              message: message || '操作失败',
              type: 'error'
            })
          }
        }, () => {
          this.listLoading = false
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
